import sys

from deezer.deezer import Deezer
from tidal.tidal import Tidal

def main():
  deezer = Deezer()
  tidal = Tidal()

  def grab_track(song_id):
    track = deezer.get_track(int(song_id))
    artists_string = ', '.join(map(lambda a: a.name, track.artists))
    print("grabbing {} by {}".format(track.title, artists_string))
    track.download(print_progress = True)
  def tidal_grab_track(song_id):
    track = tidal.get_track(int(song_id))
    artists_string = ', '.join(map(lambda a: a.name, track.artists))
    print("[tidal] grabbing {} by {} (in album {})".format(track.title, artists_string, track.album.title))
    track.download(tidal, print_progress = True)

  def login(email, password):
    user = deezer.login(email, password)
    print("logged in as %s" % user["name"])
  def tidallogin(email, password):
    user = tidal.login(email, password)
    print(user)
    print("[tidal] logged in as %s" % user["username"])

  print('''
        Welcome to...
         _|_._ _ o  _ _|
        (_(/| | ||>(/(_|
        ''')
  if len(sys.argv) > 1:
    login(sys.argv[1], sys.argv[2])
  while True:
    command = input("-> ").split(" ")

    if command[0] == 'login':
      login(command[1], command[2])
    elif command[0] == 'tidallogin':
      tidallogin(command[1], command[2])
    elif command[0] == 'grab':
      if command[1] == 'album':
        album = deezer.get_album(int(command[2]))
        print("[tidal] grabbing album %s" % album.title)
        for track in album.songs:
          grab_track(track.song_id)
      elif command[1] == 'track':
        grab_track(command[2])
      else:
        grab_track(command[1])
    elif command[0] == 'tidalgrab':
      if command[1] == 'album':
        album = tidal.get_album(int(command[2]))
        print("grabbing album %s" % album.title)
        for track in album.songs:
          tidal_grab_track(track.track_id)
      elif command[1] == 'track':
        tidal_grab_track(command[2])
      else:
        tidal_grab_track(command[1])
    elif command[0] == 'exit':
      break
    else:
      print("unknown command... :/")
